require 'depac-common/log'
require 'depac-common/constants'
require 'depac-common/constants_cbt'
require 'qingcloud/sdk'
require 'fileutils'
require 'yaml'
require 'erubis'


module Depac
  class RegisterService_CBT
    
    private 
    
    def initialize()
         Depac::Log.info("Initial RegisterService_CBT Class.........")     
    end
  
    public  
    
    
    def registerServiceOnLB(nodeInfoMap,envconfig)
	       registerToListener(nodeInfoMap,envconfig)
         bundlePolicyToBackEnd(nodeInfoMap)
      
         if envconfig['registerServiceConfig'] !=nil && envconfig['registerServiceConfig']['listeners'] !=nil       
            envconfig['registerServiceConfig']['listeners'].each do |listenerID|                
               $cloudmgr.applyLBChange(nil, listenerID['listernerID'], zone="pek2")
            end              
         end
    end 
    
    #this is main methode will be called from outside
    def registerService(nodeInfoMap,envconfig)
         registerServiceOnLB(nodeInfoMap,envconfig)
    end

    def registerToListener(nodeInfoMap,envconfig)      
        if nodeInfoMap !=nil && envconfig['registerServiceConfig'] !=nil && envconfig['registerServiceConfig']['listeners'] !=nil
          nodeInfoMap.each do |role, nodeArr|
            if nodeArr !=nil
                envconfig['registerServiceConfig']['listeners'].each do |listenerID|                             
                      nodeArr.each do |node|
                               if node['IP'] !=nil && node['lb_backend_Config'] !=nil
                                 
                                     
                                              backend_para_tmp = Hash.new
                                              backend_para_tmp = {
                                                                  :loadbalancer_listener => listenerID['listernerID'],
                                                                  :backends_N_resource_id => [node['IP']],
                                                                  :backends_N_loadbalancer_backend_name => [node['IP']]
                                                                 }    
                                              if node['containers'] != nil  # just for docker container
                                                node['containers'].each do |container|                                                         
                                                   Depac::Log.write("INFO", "RegisterService_CBT.registerToListener: register server #{node['IP']} to LB listener #{listenerID['listernerID']} with port #{container['port']}")           
                                                   
                                                    _backend_para_tmp = backend_para_tmp.clone
                                                    _backend_para_tmp[:backends_N_port]=[container['port']]
                                                   
                                                   lb_backend_ID=$cloudmgr.addLbBackend(_backend_para_tmp) 
                                                   
                                                   if lb_backend_ID !=nil
                                                      container['lb_backend_id']=lb_backend_ID
                                                      Depac::Log.write("INFO", "RegisterService_CBT.registerToListener: get lb_backend_ID: #{lb_backend_ID}") 
                                                      node['lb_backend_IDs']=Array.new if node['lb_backend_IDs']==nil
                                                      node['lb_backend_IDs'].push(lb_backend_ID) 
                                                   end
                                                end
                                              else
                                                
                                                  Depac::Log.write("INFO", "RegisterService_CBT.registerToListener: register server #{node['IP']} to LB listener #{listenerID['listernerID']}")           
                                                  lb_backend_ID=$cloudmgr.addLbBackend(backend_para_tmp) 
                                                  if lb_backend_ID !=nil
                                                     Depac::Log.write("INFO", "RegisterService_CBT.registerToListener: get lb_backend_ID: #{lb_backend_ID}") 
                                                     node['lb_backend_IDs']=Array.new if node['lb_backend_IDs']==nil
                                                     node['lb_backend_IDs'].push(lb_backend_ID)
                                                  end
                                              end
                                                
                               else    
                                    Depac::Log.write("INFO", "RegisterService_CBT.registerToListener: no specifiy lb_backend_Config, so will ignore register server #{node['IP'] } to loadbalance")               
                               end
                      end                     
                end
            end

          end
       end
    end
    
    

    
    def bundlePolicyToBackEnd(nodeInfoMap)
      #service.modify_load_balancer_backend_attributes(loadbalancer_backend: 'lbb-cudjx3uh', port: '8081', weight: 2, loadbalancer_policy_id: envconfig.vms[1]['policyID'], zone: 'pek2')      
      if nodeInfoMap != nil
           nodeInfoMap.each do |role, nodeArr|
                if role.include?('app') && nodeArr != nil
 
                     nodeArr.each do |node|
                           if node['lb_backend_Config'] !=nil && node['lb_backend_IDs'] != nil
                           Depac::Log.write("INFO", ">>>>>>>>>>>>>>>>lb_backend_IDs is #{node['lb_backend_IDs']}")   
                                if node['containers'] ==nil 
                                    node['lb_backend_IDs'].each do |lb_backend_id|
                                           #_lb_backendConfig=node['lb_backend_Config'].clone
                                      
                                           _lb_backendConfig=node['lb_backend_Config'].inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
                                                    
                                           _lb_backendConfig[:loadbalancer_backend]=lb_backend_id
                                                                           
                
                                              Depac::Log.write("INFO", "RegisterService_CBT.bundlePolicyToBackEnd: bundle LB policy with on server #{node['IP']} with lb_backend_config #{_lb_backendConfig}....")   
                                              $cloudmgr.modifyLbBackends(_lb_backendConfig)
                                    end
                                else
                                  
                                     node['containers'].each do |container|  
                                             _lb_backendConfig=node['lb_backend_Config'].inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
                                             _lb_backendConfig[:port]= container['port']
                                             _lb_backendConfig[:loadbalancer_backend]=container['lb_backend_id']  
                                             Depac::Log.write("INFO", "RegisterService_CBT.bundlePolicyToBackEnd: bundle LB policy with on server #{node['IP']} with lb_backend_config #{_lb_backendConfig}....")   
                                             $cloudmgr.modifyLbBackends(_lb_backendConfig)
                                     end
                                  
                                end
                           end
                    end
               end
           end
      end
    end
    

    def deleteBackEnd()
    end
    
    def releasePolicyFromBackEnd()
    end
              
  end
end